package com.chenhy.service;

import com.chenhy.mapper.CustomerMapper;
import com.chenhy.pojo.Bill;
import com.chenhy.pojo.Customer;
import com.chenhy.security.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerMapper customerMapper;

    @Override
    @Cacheable(value = "customer", key = "'customerList'")
    public List<Customer> queryAllCustomer() {
        return customerMapper.queryAllCustomer();
    }

    @Override
    @Cacheable(value = "customer", key = "#id")
    public Customer queryCustomerById(int id) {
        return customerMapper.queryCustomerById(id);
    }

    @Override
    public List<Customer> fuzzyBillQuery(String condition) {
        return customerMapper.fuzzyBillQuery(condition);
    }

    @Override
    public int addCustomer(Customer customer) {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        customer.setCreatedBy(loginUser.getId());
        customer.setModifyBy(loginUser.getId());
        return customerMapper.addCustomer(customer);
    }

    @Override
    @Caching(evict = {
            @CacheEvict(value = "customer", key = "#customer.id"),
            @CacheEvict(value = "customer", key = "'customerList'")
    })
    public int updateCustomer(Customer customer) {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        customer.setModifyBy(loginUser.getId());
        return customerMapper.updateCustomer(customer);
    }

    @Override
    @Caching(evict = {
            @CacheEvict(value = "customer", key = "#customer.id"),
            @CacheEvict(value = "customer", key = "'customerList'")
    })
    public int deleteCustomer(int id) {
        return customerMapper.deleteCustomer(id);
    }
}
